package token.mobileapp.controlactivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import token.mobileapp.R;
import token.mobileapp.TokenActivity;
import token.mobileapp.model.UserInfo;
import token.mobileapp.persistenceactivity.UserInfoPersistence;
import token.mobileapp.utils.Constants;
import token.mobileapp.utils.NetworkUtils;
import token.mobileapp.utils.OneTimePassword;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * token.mobileapp.controlactivity
 * Author: AVAVT
 * Date: 7/11/11
 * Time: 2:23 AM
 */
public class ViewCode extends TokenActivity implements View.OnClickListener {
    private Button buttonBack, buttonSync;
    private ImageButton buttonNewCode;
    private TextView tfCode;
    private UserInfo userInfo = null;
    private AlertDialog alertDialog = null;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_code);
        buttonBack = (Button) findViewById(R.id.code_btn_back);
        buttonBack.setOnClickListener(this);

        buttonNewCode = (ImageButton) findViewById(R.id.code_btn_newcode);
        buttonNewCode.setOnClickListener(this);

        buttonSync = (Button) findViewById(R.id.code_btn_sync);
        buttonSync.setOnClickListener(this);

        tfCode = (TextView) findViewById(R.id.code_tf_code);

        Intent intent = new Intent(this, UserInfoPersistence.class);
        startActivityForResult(intent, Constants.REQUEST_CODE_LOAD_USER);
    }

    private void getNewCode() {

        String newCode = userInfo.getSecretKey() + userInfo.getSeed();
        Long movingFactor = Long.parseLong(userInfo.getEvent());
        try {
            tfCode.setText(OneTimePassword.generateOTP(newCode.getBytes(), movingFactor, 6, false, 5));

            movingFactor++;
            userInfo.setEvent(movingFactor.toString());

            Intent intent = new Intent(this, UserInfoPersistence.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("userInfo", userInfo);
            intent.putExtras(bundle);

            startActivityForResult(intent, Constants.REQUEST_CODE_SAVE_USER);
        } catch (NoSuchAlgorithmException e) {
            displayError(e);
        } catch (InvalidKeyException e) {
            displayError(e);
        }
    }

    public void onClick(View view) {
        if (view.getId() == R.id.code_btn_back) {
            finish();
        } else if (view.getId() == R.id.code_btn_newcode) {
            buttonNewCode.setClickable(false);
            buttonSync.setClickable(false);
            getNewCode();
        } else if (view.getId() == R.id.code_btn_sync) {
            buttonNewCode.setClickable(false);
            buttonSync.setClickable(false);
            synchronize();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_CODE_LOAD_USER && resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            userInfo = (UserInfo) bundle.getSerializable("userInfo");
            getNewCode();
        } else if (requestCode == Constants.REQUEST_CODE_LOAD_USER && resultCode == Activity.RESULT_CANCELED) {
            displayError(data);
        } else if (requestCode == Constants.REQUEST_CODE_SAVE_USER && resultCode == Activity.RESULT_OK) {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
                displayAlert("Synchronization completed successfully.");
                getNewCode();
            }
            buttonNewCode.setClickable(true);
            buttonSync.setClickable(true);
        } else if (requestCode == Constants.REQUEST_CODE_SAVE_USER && resultCode == Activity.RESULT_CANCELED) {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            displayError(data);
            buttonNewCode.setClickable(true);
            buttonSync.setClickable(true);
        }
    }

    private void synchronize() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Synchronizing with server...")
                .setCancelable(false);
        alertDialog = builder.create();
        alertDialog.show();

        if (userInfo != null) {
            try {
                userInfo = NetworkUtils.synchronize(userInfo);

                Intent saveIntent = new Intent(this, UserInfoPersistence.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userInfo", userInfo);
                saveIntent.putExtras(bundle);
                startActivityForResult(saveIntent, Constants.REQUEST_CODE_SAVE_USER);
            } catch (IOException e) {
                alertDialog.dismiss();
                displayAlert("A problem occurred while trying to synchronize with server. Please make sure you are connected to the internet and try again.");
            }
        } else {
            alertDialog.dismiss();
            displayAlert("A problem occurred while performing request. Please try again.");

            Intent loadIntent = new Intent(this, UserInfoPersistence.class);
            startActivityForResult(loadIntent, Constants.REQUEST_CODE_LOAD_USER);
        }
    }
}
